package com.yunduo.module.pool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Stack;

/**
 * OSS连接池
 */
@Component
@NoArgsConstructor
@Getter
public class OSSPool {
    //密钥
    @Value("${yunduo.aliyun.oss.id}")
    private String accessKeyID;
    @Value("${yunduo.aliyun.oss.secret}")
    private String accessKeySecret;
    //节点
    @Value("${yunduo.aliyun.oss.endpoint}")
    private String endpoint;
    //bucket名称
    @Value("${yunduo.aliyun.oss.bucketName}")
    private String bucketName;
    //初始池数
    private static int count = 10;
    //池
    private Stack<OSS> clients = new Stack<>();

    //获取连接
    public OSS getConnection() {
        //每次扩容为原来的2/1
        if(null == clients || clients.size() == 0) {
            createPool();
        }
        //检查空闲元素是否过多
        if(clients.size() >= count*0.8) {
            killLazy();
        }
        return clients.pop();
    }

    //退回连接
    public void addConnection(OSS oss){
        clients.push(oss);
    }

    //栈内元素空闲超过80% 删除50%的连接
    private void killLazy(){
        int remove = (int)(count*0.5);
        int begin = 0;
        Iterator<OSS> iterator = clients.iterator();
        while (iterator.hasNext()){
            iterator.remove();
            begin = begin+1;
            if(begin == remove){
                return;
            }
        }
    }

    //扩容栈 每次2/1
    private void createPool(){
        for (int i = 0; i < count; i++){
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
            clients.push(ossClient);
        }
        count=(int)(count * 1.5);
    }
}
